package de.baumann.browser.units;

import android.os.Handler;
import android.widget.TextView;

import de.baumann.browser.R;

public class TimerUnit extends Handler {
    private int defaultTime = 60;
    private int time = defaultTime;
    private TextView textView;
    private boolean isShowEndText = true;

    private OnTimeEndListener timeEndListener;

    public void setTimeEndListener(OnTimeEndListener timeEndListener) {
        this.timeEndListener = timeEndListener;
    }

    public void setShowEndText(boolean showEndText) {
        isShowEndText = showEndText;
    }

    public TimerUnit(TextView textView) {
        this.textView = textView;
    }


    public void setTime(int time) {
        this.defaultTime = time;
        this.time = defaultTime;
    }

    public void startTime() {
        post(runnable);
        textView.setClickable(false);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time--;
            if (time == 0) {
                endtTime();
                return;
            }
            textView.setText(String.format("%ds", time));
            postDelayed(this, 1000);
        }
    };


    public void pauseTime() {
        removeCallbacks(runnable);
        time = defaultTime;
    }

    public void endtTime() {
        if (isShowEndText) {
            textView.setText(R.string.Reacquire);
        }
        textView.setClickable(true);
        removeCallbacks(runnable);
        time = defaultTime;
        if (timeEndListener != null) {
            timeEndListener.timeEnd();
        }
    }

    public interface OnTimeEndListener {
        void timeEnd();
    }

}
